import { defineStore, createPinia } from 'pinia';
import { login } from "@/api/user.js";
import piniaPersist from 'pinia-plugin-persist'
// 常量路由
import { routes } from "@/router/index.js";

const pinia = createPinia()
pinia.use(piniaPersist)

export const useUserStore = defineStore('user', {
    persist:
    {
        enabled: true,
        strategies: [{ key: 'username', storage: localStorage }]
    },
    // id: 'user',
    state: () => ({
        token: localStorage.getItem('token'),
        menuRoutes: routes,//菜单路由
        userName: "",
        isColleable: false,//左侧菜单是否可折叠
    }),
    actions: {
        //登录
        login(form) {
            return new Promise((resolve, reject) => {
                login(form).then(res => {
                    if (res.code == 200) {
                        this.token = res.data.token;
                        this.userName = res.data.name;
                        localStorage.setItem('token', res.data.token);
                        localStorage.setItem('username', res.data.name);
                        resolve();
                    } else {
                        reject(new Error(res.message));
                    }
                }).catch(err => {
                    reject(new Error(err.message));
                });

            })
        },
        loginOut() {
            return new Promise((resolve, reject) => {
                this.token = "";
                localStorage.removeItem('token');
                resolve();
            })
        }

    }
});